package com.tfos.study.mvc.web.data.binder.validator;

import com.tfos.study.mvc.web.data.binder.entity.Organization;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * 类功能说明：手机号验证类 <br/>
 * 公司名称：TF（腾飞）开源 <br/>
 * 作者：luorongxi <br/>
 */
@Component
public class PhoneValidator implements Validator {

    /**
     * 检验参数是否验证成功的实例类
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        //isAssignableFrom()方法是判断是否为某个类的父类，instanceof关键字是判断是否某个类的子类。
        return Organization.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        Organization org = (Organization)o;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "","phone is empty");
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,2-9]))\\d{8}$";
        if(!org.getPhone().matches(regex)){
            errors.rejectValue("phone","", "Please enter a valid mobile phone number");
        }
    }
}
